'use client'

import React, { useState, useEffect } from 'react'
import {
    Card,
    Form,
    Input,
    InputNumber,
    Select,
    Switch,
    Slider,
    Button,
    Space,
    Divider,
    Typography,
    Tooltip,
    Alert,
    Row,
    Col,
    Collapse
} from 'antd'
import {
    SettingOutlined,
    InfoCircleOutlined,
    ReloadOutlined,
    SaveOutlined
} from '@ant-design/icons'
import { Task, TaskParams, TaskConfig } from '@/types/task'

const { Title, Text } = Typography
const { Option } = Select
const { Panel } = Collapse

interface TaskParameterConfigProps {
    task: Task
    onParametersChange: (params: TaskParams) => void
    onConfigSave?: (config: TaskConfig) => void
    disabled?: boolean
}

export const TaskParameterConfig: React.FC<TaskParameterConfigProps> = ({
    task,
    onParametersChange,
    onConfigSave,
    disabled = false
}) => {
    const [form] = Form.useForm()
    const [parameters, setParameters] = useState<TaskParams>(task.config.parameters as TaskParams)
    const [hasChanges, setHasChanges] = useState(false)

    useEffect(() => {
        // 初始化表单值
        form.setFieldsValue(parameters)
    }, [task, form])

    const handleParameterChange = (changedValues: Partial<TaskParams>, allValues: TaskParams) => {
        setParameters(allValues)
        setHasChanges(true)
        onParametersChange(allValues)
    }

    const handleReset = () => {
        const defaultParams = task.config.parameters as TaskParams
        setParameters(defaultParams)
        form.setFieldsValue(defaultParams)
        setHasChanges(false)
        onParametersChange(defaultParams)
    }

    const handleSave = () => {
        if (onConfigSave) {
            const updatedConfig: TaskConfig = {
                ...task.config,
                parameters: parameters
            }
            onConfigSave(updatedConfig)
            setHasChanges(false)
        }
    }

    const renderDetectionParameters = () => (
        <Space direction="vertical" size="middle" className="w-full">
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name="confidenceThreshold"
                        label={
                            <Space>
                                <span>置信度阈值</span>
                                <Tooltip title="检测结果的最小置信度，低于此值的检测将被过滤">
                                    <InfoCircleOutlined />
                                </Tooltip>
                            </Space>
                        }
                        initialValue={0.5}
                    >
                        <Slider
                            min={0.1}
                            max={1.0}
                            step={0.05}
                            marks={{
                                0.1: '0.1',
                                0.5: '0.5',
                                1.0: '1.0'
                            }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name="nmsThreshold"
                        label={
                            <Space>
                                <span>NMS阈值</span>
                                <Tooltip title="非极大值抑制阈值，用于去除重叠的检测框">
                                    <InfoCircleOutlined />
                                </Tooltip>
                            </Space>
                        }
                        initialValue={0.4}
                    >
                        <Slider
                            min={0.1}
                            max={0.9}
                            step={0.05}
                            marks={{
                                0.1: '0.1',
                                0.4: '0.4',
                                0.9: '0.9'
                            }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name="maxDetections"
                        label="最大检测数量"
                        initialValue={100}
                    >
                        <InputNumber
                            min={1}
                            max={1000}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name="modelVersion"
                        label="模型版本"
                        initialValue="v1.0"
                    >
                        <Select disabled={disabled}>
                            <Option value="v1.0">v1.0 - 标准模型</Option>
                            <Option value="v1.1">v1.1 - 优化模型</Option>
                            <Option value="v2.0">v2.0 - 最新模型</Option>
                        </Select>
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item
                name="enableMultiScale"
                label="启用多尺度检测"
                valuePropName="checked"
                initialValue={true}
            >
                <Switch disabled={disabled} />
            </Form.Item>
        </Space>
    )

    const renderClassificationParameters = () => (
        <Space direction="vertical" size="middle" className="w-full">
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name="batchSize"
                        label="批处理大小"
                        initialValue={32}
                    >
                        <InputNumber
                            min={1}
                            max={128}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name="topK"
                        label="Top-K结果"
                        initialValue={5}
                    >
                        <InputNumber
                            min={1}
                            max={10}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item
                name="modelType"
                label="分类模型"
                initialValue="resnet50"
            >
                <Select disabled={disabled}>
                    <Option value="resnet50">ResNet-50</Option>
                    <Option value="efficientnet">EfficientNet</Option>
                    <Option value="vit">Vision Transformer</Option>
                </Select>
            </Form.Item>

            <Form.Item
                name="enableTTA"
                label="启用测试时增强"
                valuePropName="checked"
                initialValue={false}
            >
                <Switch disabled={disabled} />
            </Form.Item>
        </Space>
    )

    const renderSegmentationParameters = () => (
        <Space direction="vertical" size="middle" className="w-full">
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name="outputResolution"
                        label="输出分辨率"
                        initialValue="original"
                    >
                        <Select disabled={disabled}>
                            <Option value="original">原始分辨率</Option>
                            <Option value="512x512">512x512</Option>
                            <Option value="1024x1024">1024x1024</Option>
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name="postProcessing"
                        label="后处理方法"
                        initialValue="crf"
                    >
                        <Select disabled={disabled}>
                            <Option value="none">无</Option>
                            <Option value="crf">条件随机场</Option>
                            <Option value="morphology">形态学处理</Option>
                        </Select>
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name="minRegionSize"
                        label="最小区域大小"
                        initialValue={100}
                    >
                        <InputNumber
                            min={10}
                            max={10000}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name="smoothingIterations"
                        label="平滑迭代次数"
                        initialValue={3}
                    >
                        <InputNumber
                            min={0}
                            max={10}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item
                name="enableEdgeRefinement"
                label="启用边缘细化"
                valuePropName="checked"
                initialValue={true}
            >
                <Switch disabled={disabled} />
            </Form.Item>
        </Space>
    )

    const renderPreprocessingParameters = () => (
        <Space direction="vertical" size="middle" className="w-full">
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name={['preprocessing', 'normalize']}
                        label="标准化"
                        valuePropName="checked"
                        initialValue={true}
                    >
                        <Switch disabled={disabled} />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name={['preprocessing', 'windowLevel', 'center']}
                        label="窗位中心"
                        initialValue={400}
                    >
                        <InputNumber
                            min={-1000}
                            max={3000}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item
                        name={['preprocessing', 'windowLevel', 'width']}
                        label="窗宽"
                        initialValue={1600}
                    >
                        <InputNumber
                            min={1}
                            max={4000}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        name={['preprocessing', 'resize', 'width']}
                        label="调整宽度"
                        initialValue={512}
                    >
                        <InputNumber
                            min={128}
                            max={2048}
                            style={{ width: '100%' }}
                            disabled={disabled}
                        />
                    </Form.Item>
                </Col>
            </Row>
        </Space>
    )

    const renderTaskSpecificParameters = () => {
        switch (task.type) {
            case 'detection':
                return renderDetectionParameters()
            case 'classification':
                return renderClassificationParameters()
            case 'segmentation':
                return renderSegmentationParameters()
            default:
                return (
                    <Alert
                        message="未知任务类型"
                        description="无法显示此任务类型的参数配置"
                        type="warning"
                        showIcon
                    />
                )
        }
    }

    return (
        <Card
            title={
                <Space>
                    <SettingOutlined />
                    <span>任务参数配置</span>
                </Space>
            }
            extra={
                <Space>
                    {hasChanges && (
                        <Text type="warning" className="text-sm">
                            有未保存的更改
                        </Text>
                    )}
                    <Button
                        size="small"
                        icon={<ReloadOutlined />}
                        onClick={handleReset}
                        disabled={disabled || !hasChanges}
                    >
                        重置
                    </Button>
                    {onConfigSave && (
                        <Button
                            size="small"
                            type="primary"
                            icon={<SaveOutlined />}
                            onClick={handleSave}
                            disabled={disabled || !hasChanges}
                        >
                            保存
                        </Button>
                    )}
                </Space>
            }
        >
            <Form
                form={form}
                layout="vertical"
                onValuesChange={handleParameterChange}
                disabled={disabled}
            >
                <Collapse defaultActiveKey={['task', 'preprocessing']} ghost>
                    <Panel
                        header={
                            <Title level={5} className="mb-0">
                                任务特定参数
                            </Title>
                        }
                        key="task"
                    >
                        {renderTaskSpecificParameters()}
                    </Panel>

                    <Panel
                        header={
                            <Title level={5} className="mb-0">
                                预处理参数
                            </Title>
                        }
                        key="preprocessing"
                    >
                        {renderPreprocessingParameters()}
                    </Panel>

                    <Panel
                        header={
                            <Title level={5} className="mb-0">
                                高级选项
                            </Title>
                        }
                        key="advanced"
                    >
                        <Space direction="vertical" size="middle" className="w-full">
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Form.Item
                                        name="timeout"
                                        label="超时时间 (秒)"
                                        initialValue={300}
                                    >
                                        <InputNumber
                                            min={60}
                                            max={3600}
                                            style={{ width: '100%' }}
                                            disabled={disabled}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        name="priority"
                                        label="任务优先级"
                                        initialValue={1}
                                    >
                                        <Select disabled={disabled}>
                                            <Option value={0}>低</Option>
                                            <Option value={1}>普通</Option>
                                            <Option value={2}>高</Option>
                                            <Option value={3}>紧急</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Form.Item
                                name="enableGPU"
                                label="启用GPU加速"
                                valuePropName="checked"
                                initialValue={true}
                            >
                                <Switch disabled={disabled} />
                            </Form.Item>

                            <Form.Item
                                name="debugMode"
                                label="调试模式"
                                valuePropName="checked"
                                initialValue={false}
                            >
                                <Switch disabled={disabled} />
                            </Form.Item>
                        </Space>
                    </Panel>
                </Collapse>
            </Form>
        </Card>
    )
}

export default TaskParameterConfig